using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace deckAnalyser.Support
{


    public class DBWrapper
    {
        private static Dictionary<String,String> attachedDBs = new Dictionary<String,String>();
        private static SQLiteConnection connection = null;
        
        private static bool isOpen = false;
        public static bool IsOpen { get { return isOpen; } }

        public static void Open(String path,String name)
        {
            if (isOpen) throw new Exception("Unable to open database. Datbase connection is already open.");

            connection = new SQLiteConnection("Data Source=" + Path.Combine(path,name)); ;
            connection.Open();
            isOpen = true;
        }

        public static void Close()
        {
            if (!isOpen) throw new Exception("Unable to close database. Datbase connection is not open.");

            connection.Close();
            isOpen = false;
        }

        public static void Attach(String path, String name, String alias)
        {
            if (!isOpen) throw new Exception("Unable to attach database. Datbase connection is not open.");

            DBWrapper.ExecuteNonQuery("attach database '"+Path.Combine(path,name)+"' as "+alias+";");            
        }

        public static int ExecuteNonQuery(string sql)
        {
            int rowsUpdated = 0;
            SQLiteCommand command = new SQLiteCommand(connection);
            command.CommandText = sql;
            rowsUpdated = command.ExecuteNonQuery();
            return rowsUpdated;
        }

        public static DataTable GetDataTable(string sql)
        {
            DataTable retVal = new DataTable();

            SQLiteCommand command = new SQLiteCommand(connection);
            command.CommandText = sql;
            SQLiteDataReader reader = command.ExecuteReader();
            retVal.Load(reader);
            reader.Close();

            return retVal;
        }

        public static string ExecuteScalar(string sql)
        {
            SQLiteCommand command = new SQLiteCommand(connection);
            command.CommandText = sql;
            object value = command.ExecuteScalar();
            if (value != null)
            {
                return value.ToString();
            }
            return "";
        }
    }
}
